<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 <h1>The Ajax 02 Page</h1>
 <fieldset>
    <legend>Ajax 表单请求</legend>
    <form>
       <input type="text" name="name" id="nameId" onblur="doCheck()" onfocus="doClear()">
       <input type="button" onclick="doSave()" value="Save">
    </form>
    <span id="result"></span>
 </fieldset>
 <script type="text/javascript">
     function doClear(){
    	 document.getElementById("result").innerHTML="";
     }
     
     function doSave(){
    	//1.创建XHR对象
     	var xhr=new XMLHttpRequest();
     	//2.设置状态监听
     	xhr.onreadystatechange=function(){
     	     if(xhr.readyState==4&&xhr.status==200){
     	          document.getElementById("result").innerHTML="<font color='red'>"+xhr.responseText+"</font>";
     	     }
     	};
     	//3.打开链接
     	//var name=document.getElementById("nameId").value;
     	var  name=document.forms[0].name.value;
     	xhr.open("POST","/doSave",true);
     	//post请求要设置请求头(规定)
     	xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
     	//4.发送请求
     	xhr.send("name="+name);//Post请求send方法传值 
     }
     
     function doCheck(){//在此函数中向服务端发起异步请求,检测name是否存在
    	//1.创建XHR对象
    	var xhr=new XMLHttpRequest();
    	//2.设置状态监听
    	xhr.onreadystatechange=function(){
    	     if(xhr.readyState==4&&xhr.status==200){
    	          document.getElementById("result").innerHTML="<font color='red'>"+xhr.responseText+"</font>";
    	     }
    	};
    	//3.打开链接
    	//var name=document.getElementById("nameId").value;
    	var  name=document.forms[0].name.value;
    	console.log("name",name);
    	xhr.open("GET","/doCheck?name="+name,true);
    	//4.发送请求
    	xhr.send(null);//Get请求send方法传值
     }
     
 </script>
</body>
</html>